/**
 * Created by Harvey Zhao on 16-8-27.
 */
import fetch from 'isomorphic-fetch'

//登录
export const LOGIN_REQUEST = 'LOGIN_REQUEST';
export const LOGIN_RECEIVE = 'LOGIN_RECEIVE';

export function action_login(user) {
    return (dispatch, getState) => {
        if (!getState().login.isLogin && !getState().login.isLogining) {
            dispatch({
                type: LOGIN_REQUEST,
                user
            })
            fetch('http://localhost:3000/users/login?username=' + user.username + '&password=' + user.password, {
                credentials: 'same-origin'
            }).then(response => response.json())
                .then(json => dispatch({
                    type: LOGIN_RECEIVE,
                    user,
                    isLogin: json.status
                }))
        }
    }
}


//登出
export const LOGOUT = 'LOGOUT';

export function action_logout() {
    return dispatch => {
        fetch(`http://localhost:3000/users/logout`, {
            credentials: 'same-origin'
        }).then(response => response.json()).then(
            data => {
                if (data.status)
                    return dispatch({
                        type: LOGOUT
                    })
            })
    }
}

//二维码请求
export const QR_REQUEST = 'QR_REQUEST';
export const QR_RECEIVE = 'QR_RECEIVE';

export function qr(code) {
    return (dispatch) => {
        dispatch({
            type: QR_REQUEST,
        });
        fetch(`http://localhost:3000/users/qr?code=${code}`)
            .then(response => response.json())
            .then(json => dispatch({
                type: QR_RECEIVE,
                img: json.img
            }))
    }
}